package client

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

func Run() {
	var server string
	var token string
	var path string
	flag.StringVar(&server, "s", "http://localhost:8080", "server address")
	flag.StringVar(&token, "token", "admin", "auth token")
	flag.StringVar(&path, "f", "", "image file path")
	flag.Parse()
	image, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		return
	}
	ext, _ := strings.CutPrefix(strings.ToLower(filepath.Ext(path)), ".")
	req, err := http.NewRequest("POST", fmt.Sprintf("%s/upload?type=%s", server, ext), image)
	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("token", token)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}

	b, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	var res struct {
		Name  string `json:"name"`
		Error string `json:"error"`
	}
	err = json.Unmarshal(b, &res)
	if err != nil {
		fmt.Println(err)
		return
	}
	if res.Error != "" {
		fmt.Println(res.Error)
		return
	}
	fmt.Printf("Upload Success:\n%s/img/%s_2s.jpg", server, res.Name)
}
